//得到购买商品的ID
var productId = getQuery("productId");
window.onload = function (){
    if(productId != null && productId != ''){
        buy();
    }
    else{
        showShop();
    }

}

/**
 * 显示购物车信息
 */
function showShop(){
    axios.get("/custom/shop/findByUser",null).then(e =>{
        var info = e.data;
        var total = 0;
        var str = "";
        for(var i=0;i<info.length;i++){
            var obj = info[i];
            str += `<tr><td>${obj.product.name}</td><td>${obj.product.price}</td>
            <td>${obj.product.factory}</td>
            <td><input type="number" value="${obj.num}" onblur="updateNum(${obj.id},this)"></td>
            <td>${obj.product.price * obj.num}</td>
            <td><a href="javascript:del(${obj.id})">移除商品</a></td></tr>`;

            total += obj.product.price * obj.num;
        }
        $("shopData").innerHTML = str;
        $("totalSpan").innerHTML = total;
    });
}



/**
 * 移除商品
 * @param shopId 购物车ID
 */
function del(shopId){
    axios.get("/custom/shop/del",{
        params:{
            shopId
        }
    }).then(e =>{
       if(e.data == "ok"){
           showShop();
       }
    });
}

/**
 * 购买商品
 */
function buy(){
     axios.get("/custom/shop/buy",{
        params:{
            productId
        }
    }).then(e =>{
        if(e.data == "ok"){
            showShop();
        }
    });
}

/**
 * 修改商品购买数量
 * @param shopId 购物车ID
 * @param txtObj 数量文本框对象
 */
function updateNum(shopId,txtObj){
    axios.get("/custom/shop/update",{
        params:{
            shopId,
            newNum:txtObj.value
        }
    }).then(e =>{
        if(e.data != "ok"){
            alert("购物车数量更新失败");
        }
        else{
            showShop();
        }
    });
}

function addOrder(){
    location.href = "/custom/addOrder.html?totalPrice="
        +$("totalSpan").innerHTML;
}